#!/bin/bash

# 删除旧文件并复制新文件
if rm -rf /app/node/* && cp -R /app/pro/cz-23yw/hws-node/* /app/node; then
    echo "文件复制成功。"
else
    echo "文件复制失败。"
    exit 1
fi

# 添加端口映射
echo "**********************添加端口映射**********************"
DOCKER1="/app/pro/cz-23yw/docker-compose-node+3001.yml"
TAG_DOCKER="/app/docker-compose.yml"
if rm -rf $TAG_DOCKER && cp$DOCKER1 $TAG_DOCKER; then
    echo "端口映射配置文件复制成功。"
else
    echo "端口映射配置文件复制失败。"
    exit 1
fi

# 杀死并删除容器
echo "**********************重新创建所有容器**********************"
cd /app
if docker kill node nginx && docker rm node nginx; then
    echo "容器已删除。"
else
    echo "容器删除失败。"
    exit 1
fi

# 启动新容器
if docker-compose up -d; then
    echo "容器已启动。"
else
    echo "容器启动失败。"
    exit 1
fi

# 修改数据库配置
echo "**********************修改数据库配置**********************"
FILE="/app/node/config.development.js"
TARGET_HOST=$(hostname -I | awk '{print$1}')
if [ -f "$FILE" ]; then
    CONTENT=$(cat "$FILE")
    HOST_COUNT=$(echo "$CONTENT" | grep -o "host:'$TARGET_HOST'," | wc -l)
    if [ "$HOST_COUNT" -eq 2 ]; then
        echo "数据库配置正确。"
    else
        sed -i "s/host:[^,]*/host:'$TARGET_HOST'/g" "$FILE"
        echo "数据库配置已更新。"
    fi
else
    echo "数据库配置文件不存在。"
    exit 1
fi

# 初始化数据库
echo "**********************初始化**********************"
if sh /app/pro/cz-23yw/hws-node/mysql_check.sh; then
    echo "数据库初始化成功。"
else
    echo "数据库初始化失败。"
    exit 1
fi

# 修改后端请求ip配置
echo "**********************修改后端请求ip配置**********************"
FILE1="/app/node/admin/H5/js/config.js"
if [ -f "$FILE1" ]; then
    CONTENT1=$(cat "$FILE1")
    HOST_COUNT1=$(echo "$CONTENT1" | grep -o "host:'$TARGET_HOST:3001'," | wc -l)
    if [ "$HOST_COUNT1" -eq 1 ]; then
        echo "后端请求IP配置正确。"
    else
        sed -i "s|APIURL:[^,]*|APIURL:'http://$TARGET_HOST:3001'|g" "$FILE1"
        echo "后端请求IP配置已更新。"
    fi
else
    echo "后端请求IP配置文件不存在。"
    exit 1
fi

# 启动项目
echo "**********************启动项目**********************"
if docker exec -i node nohup npm run dev &; then
    echo "项目已启动。"
else
    echo "项目启动失败。"
    exit 1
fi

# 退出容器
echo "退出容器"
docker exit
